package com.genius.util.Encryption;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

import static com.genius.util.ConstPool.RedisConstPool.LOGIN_TOKEN_TTL;

public class JWTEncryption implements EncryptionUtil {

    private final static String SIGNATURE = "!TIME42";

    public static String Encrypte(Map<String,String> map) {
        JWTCreator.Builder builder = JWT.create();
        map.forEach((k,v)->{
            builder.withClaim(k,v);
        });
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.HOUR,(int)LOGIN_TOKEN_TTL);
        builder.withExpiresAt(instance.getTime());
        return builder.sign(Algorithm.HMAC256(SIGNATURE));
    }

    public static DecodedJWT Decrypt(String token){
        return JWT.require(Algorithm.HMAC256(SIGNATURE)).build().verify(token);
    }

    public static void verify(String token){
        JWT.require(Algorithm.HMAC256(SIGNATURE)).build().verify(token);
    }

    public static Claim getTokenValue(String token, String value){
        DecodedJWT decodedJWT = Decrypt(token);
        return decodedJWT.getClaim(value);
    }

    public static DecodedJWT getDecodeJWT(String token){
        return Decrypt(token);
    }

    public static String GenerateToken(String username){
        Map<String,String> payload = new HashMap<>();
        payload.put("username",username);
        String token = JWTEncryption.Encrypte(payload);
        return token;
    }

    public static String GenerateToken(String username,String userId){
        Map<String,String> payload = new HashMap<>();
        payload.put("username",username);
        payload.put("uid",userId);
        String token = JWTEncryption.Encrypte(payload);
        return token;
    }
}
